<?php

class IndexController extends G4T_Controller
{
    const NEWS_PER_PAGE = 10;
    const ID_OF_RUBRIC = 25;
    const NEWS_FOR_RUBRIC = 2;

    private $_user;

    public function init()
    {
        parent::init();
        $this->_user = \Zend_Auth::getInstance()->getStorage()->read();
    }

    public function indexAction()
    {
        if ($this->_isMobile()) {
            $this->_redirect("/mobile");
        }
        else {
            $page = (int)$this->_getParam('page');
            $newsManagers = new \Managers\News();
            $newsManagers->setLimit(self::NEWS_PER_PAGE);
            $offset = $page > 0 ? ($page - 1) * self::NEWS_PER_PAGE : 0;
            $newsManagers->setOffset($offset);
            $news = $newsManagers->getListWithCommentsCount();
            $total = $newsManagers->getCount(true);
            $this->displayPaginantor($total, $page, self::NEWS_PER_PAGE);
            $this->view->news = $news;
            $topnews = $newsManagers->getTopNews();
            $this->view->topnews = $topnews;
            $rubrics = $newsManagers->getRub4News();
            $this->view->rubrics = $rubrics;


//             Вывод 1 конкретной рубрики внизу страницы по 2 новости
            $rubricManager = new \Managers\Rubrics();
            $rubrica = $rubricManager->getById(self::ID_OF_RUBRIC);
            if ($rubrica) $this->view->rubricname = $rubrica['name'];
            $newsBuilder = new \Managers\Builder\NewsBuilder();
            $newsBuilder->setRubric(self::ID_OF_RUBRIC);

            $offset = $this->getOffcetToRubric($page);
            $newsBuilder->setLimit(self::NEWS_FOR_RUBRIC, $offset);
            $this->view->onerubricnews = $newsBuilder->getList();

        }
    }

    public function allnewsAction()
    {

        $page = (int)$this->_getParam('page');
        $newsManagers = new \Managers\News();
        $newsManagers->setLimit(self::NEWS_PER_PAGE);
        $offset = $this->getOffet($page);
        $newsManagers->setOffset($offset);
        $news = $newsManagers->getListWithCommentsCount();
        $total = $newsManagers->getCount(true);
        $this->displayPaginantor($total, $page, self::NEWS_PER_PAGE);

        $this->view->news = $news;

        $topnews = $newsManagers->getTopNews();
        $this->view->topnews = $topnews;
        $rubrics = $newsManagers->getRub4News();
        $this->view->rubrics = $rubrics;


        $this->renderScript('/index/allnews.phtml');
    }

    private function _isMobile()
    {
        $browser = new \Managers\Browser($_SERVER['HTTP_USER_AGENT']);
        return ($browser->getPlatform() == \Managers\Browser::PLATFORM_IPHONE) ||
            ($browser->getPlatform() == \Managers\Browser::PLATFORM_BLACKBERRY) ||
            ($browser->getPlatform() == \Managers\Browser::PLATFORM_ANDROID) ||
            ($browser->getBrowser() == \Managers\Browser::BROWSER_OPERA_MINI) ||
            //            ($browser->getBrowser() == \Managers\Browser::BROWSER_CHROME) ||

            ($browser->getPlatform() == \Managers\Browser::PLATFORM_IPOD) ||
            ($browser->getPlatform() == \Managers\Browser::PLATFORM_IPAD);
    }


    public function rssAction()
    {
        $newsManagers = new \Managers\News();
        $newsManagers->setLimit(self::NEWS_PER_PAGE);
        $this->view->news = $newsManagers->getRecent();
        $this->_helper->layout->disableLayout();
        $this->getResponse()->setHeader('Content-Type', 'text/xml');
    }

    public function newsAction()
    {
        $this->saveCurrentUrl();
        $newsManager = new \Managers\News();
        $article = $newsManager->getByIdWithCommentsAndSimilar($this->_getParam('id'));
        if (!$article) {
            $this->_flashMessenger->addMessage('Article not found.', Lib_Flash::ERROR, Lib_Flash::LATER);
            $this->_redirect('/');
        }
        $newsManager->incrementViews($this->_getParam('id'));
        $this->view->article = $article;
        $form = $this->getCommentFormBuilder()->getForm();
        $form->populate(array('news' => $article['id']));
        $this->view->form = $form;
    }

    public function printAction()
    {
        $this->_helper->layout->setLayout('print-layout');
        $newsManager = new \Managers\News();
        $article = $newsManager->getByIdWithCommentsAndSimilar($this->_getParam('id'));
        if (!$article) {
            $this->_flashMessenger->addMessage('Article not found.', Lib_Flash::ERROR, Lib_Flash::LATER);
            $this->_redirect('/');
        }
        $this->view->article = $article;

    }

    public function tagAction()
    {
        $tagsManager = new \Managers\Tags();
        $tag = $tagsManager->getByIdWithNews($this->_getParam('id'));
        $this->view->tag = $tag;
        if (!$tag) {
            $this->_flashMessenger->addMessage('Tag not found.', Lib_Flash::ERROR, Lib_Flash::LATER);
            $this->_redirect('/');
        }
        $this->view->news = $tag['news'];
    }

    public function issueAction()
    {
        $page = (int)$this->_getParam('page');
        $issueManager = new \Managers\Issue();
        $issue = $issueManager->getById($this->_getParam('id'));
        $this->view->issue = $issue;
        if (!$issue) {
            $this->_flashMessenger->addMessage("Номер газеты не найден.", Lib_Flash::ERROR, Lib_Flash::LATER);
            $this->_redirect('/');
        }
        $newsBuilder = new \Managers\Builder\NewsBuilder();
        $newsBuilder->setIssue($issue['id']);
        $total = $newsBuilder->getTotal();
        $this->view->total = $total;
        $this->displayPaginantor($total, $page, self::NEWS_PER_PAGE);

        $offset = $this->getOffet($page);
        $newsBuilder->setLimit(self::NEWS_PER_PAGE, $offset);
        $news = $newsBuilder->getList();
        $this->view->news = $news;

    }

    public function rubricAction()
    {
        $page = (int)$this->_getParam('page');
        $rubricManager = new \Managers\Rubrics();
        $rubric = $rubricManager->getById($this->_getParam('id'));
        $this->view->rubric = $rubric;
        if (!$rubric) {
            $this->_flashMessenger->addMessage("Рубрика не найдена.", Lib_Flash::ERROR, Lib_Flash::LATER);
            $this->_redirect('/');
        }
        $newsBuilder = new \Managers\Builder\NewsBuilder();
        $newsBuilder->setRubric($rubric['id']);

        $total = $newsBuilder->getTotal();
        $this->displayPaginantor($total, $page, self::NEWS_PER_PAGE);

        $offset = $this->getOffet($page);
        $newsBuilder->setLimit(self::NEWS_PER_PAGE, $offset);
        $this->view->news = $newsBuilder->getList();
    }

    private function getOffet($page)
    {
        return $page > 0 ? ($page - 1) * self::NEWS_PER_PAGE : 0;
    }

    private function getOffcetToRubric($page)
    {
        return $page > 0 ? ($page - 1) * self::NEWS_FOR_RUBRIC : 0;
    }

    public function aboutAction()
    {

    }

    public function inworkAction()
    {

    }

    public function contactsAction()
    {
        $this->view->status = $this->_getParam('send');
        if ($this->_request->isPost()) {

            $email = $this->_getParam('email-guest');
            $subject = $this->_getParam('email-subject');
            $message = $this->_getParam('email-message');
            $mailManager = new  \Managers\Mailsend();

            $mailManager->sendEmail($email, $subject, $message);
            $this->_redirect(Zend_Registry::get('config')->resources->frontController->baseUrl . "/index/contacts/send/1");

        }
    }

    private function getCommentFormBuilder()
    {
        $formBuilder = \G4T\Form\FormBuilder::createFormBuilder(\Managers\Comments::TABLE,
            array(
                'action' => '/comments/add',
                'class' => 'comment-add-form'
            )
        )
//            ->addField('email', 'email', array('label' => 'Эмайл:'))
            ->addField('text', 'text', array('label' => 'Cообщение:', 'rows' => '5', 'style' => 'width:100%'))
//            ->addField('token', 'hash')
            ->addField('news', 'hidden')
            ->addField('parent', 'hidden', array('required' => false))
            ->addField('submit', 'submit', array('label' => 'Добавить', 'class' => 'btn', 'style' => 'margin: -50px 0 0 0;float: right;'));
        return $formBuilder;
    }


}
